package com.dongdong.shiro;

import com.dongdong.api.UserAPI;
import com.dongdong.em.Result;
import com.dongdong.model.TbUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserAPI userAPI;

    //授权管理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证管理
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        Result<TbUser> result = userAPI.getUserByName(usernamePasswordToken.getUsername());
        TbUser userByName = result.getData();
        if (userByName == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(userByName, userByName.getPassword(), ByteSource.Util.bytes(userByName.getSalt()), "user");
    }
}
